<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>

</body>
<script>
  let list = [
    {id: 1, name: '节点1', pid: ''},
    {id: 11, name: '节点1-1', pid: 1},
    {id: 111, name: '节点1-1-1', pid: 11},
    {id: 12, name: '节点1-2', pid: 1},
    {id: 2, name: '节点2', pid: ''},
    {id: 21, name: '节点2-1', pid: 2}
  ]
  /*
  目标结果
  let list = [
    {id: 1, name: '节点1', pid: '' ,children: [
      {id: 11, name: '节点1-1', pid: 1, children: [
         {id: 111, name: '节点1-1-1', pid: 11}
      ]},
      {id: 12, name: '节点1-2', pid: 1},
    ]},
    {id: 2, name: '节点2', pid: '', children: [
      {id: 21, name: '节点2-1', pid: 2}
    ]},
  ]
  */
  //方式1-不用递归,简单方式
  /*
  //找节点children
  list.forEach(t=>{
    //filter数组当中查找,满足条件所有元素
    let children = list.filter(m=> m.pid === t.id)
    if(children.length>0){
      t.children = children
    }
  })
  //找一级元素
  let result = list.filter(t=> t.pid === '')
  console.log(result)
  */

  //简单的递归
  /*
  function translateListToTree(pid){
    let result = list.filter(m=> m.pid === pid)
    //步骤2,继续给孩子找孩子
    result.forEach(t=>{
      let children = translateListToTree(t.id)
      if(children.length>0){
        t.children = children
      }
    })
    return result
  }
  //步骤1-传id找孩子
  console.log(translateListToTree(''))
  */
 //完善递归,不要有全局变量
  function translateListToTree(arr, pid){
    let result = arr.filter(m=> m.pid === pid)
    //步骤2,继续给孩子找孩子
    result.forEach(t=>{
      let children = translateListToTree(arr, t.id)
      if(children.length>0){
        t.children = children
      }
    })
    return result
  }
  console.log(translateListToTree(list, ''))
</script>
</html>
